#include "stdafx.h"
#include "loadTexture.h"
using namespace std;

MyTexture LoadImageToTexture(char* filename)
{
	int w,h;
	FREE_IMAGE_FORMAT formato = FreeImage_GetFileType(filename,0);//Automatocally detects the format(from over 20 formats!)
	FIBITMAP* imagen = FreeImage_Load(formato, filename);
	
	FIBITMAP* temp = imagen;
	imagen = FreeImage_ConvertTo32Bits(imagen);
	FreeImage_Unload(temp);
	
	w = FreeImage_GetWidth(imagen);
	h = FreeImage_GetHeight(imagen);
	cout<<"The size of the image is: "<<filename<<" is "<<w<<"*"<<h<<endl; //Some debugging code
	
	GLubyte* textura = new GLubyte[4*w*h];
	char* pixeles = (char*)FreeImage_GetBits(imagen);
	//FreeImage loads in BGR format, so you need to swap some bytes(Or use GL_BGR).
	
	for(int j= 0; j<w*h; j++){
		textura[j*4+0]= pixeles[j*4+2];
		textura[j*4+1]= pixeles[j*4+1];
		textura[j*4+2]= pixeles[j*4+0];
		textura[j*4+3]= pixeles[j*4+3];
		//cout<<j<<": "<<textura[j*4+0]<<"**"<<textura[j*4+1]<<"**"<<textura[j*4+2]<<"**"<<textura[j*4+3]<<endl;
	}
	return MyTexture(textura,w,h);
}